package com.thread.concurrentTest;

import org.junit.Test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class CyclicBarrierTest {

    @Test
    public void test1() {
        // 设置阈值和达到阈值后要执行的Runnable实现
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
            System.out.println("集齐7颗龙珠");
        });
        for (int i = 0; i < 7; ++i) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 星龙珠已收集");
                try {
                    cyclicBarrier.await(); // 在这里会阻塞住,直到await的数量达到cyclicBarrier设置的阈值,所有阻塞的线程才会同时都往下走
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("释放龙珠: " + Thread.currentThread().getName());
            }, String.valueOf(i)).start();
        }
    }

    @Test
    public void test2() {
        try {
            System.out.println("before interrupt");
            Thread.currentThread().interrupt();
            System.out.println("after interrupt");
        } catch (Exception e) {
            System.out.println("catchException");
            e.printStackTrace();
        } finally {
            System.out.println("finally");
        }
    }

}
